﻿using Microsoft.SharePoint.Publishing.Fields;
using Repo.Interfaces;

namespace Repo.FieldTypes {
	
	public class SPPublishingImageField : IComplexFieldType {
		
		private string _originalHtml;

		public string Html {
			get {
				var newHtml = string.Empty;
				if (!string.IsNullOrEmpty(ImageLink)) {
					newHtml += "<a href=\"" + ImageLink + "\""
							  + (!string.IsNullOrEmpty(AnchorClass) ? " class=\"" + AnchorClass + "\"" : string.Empty)
							  + ">";
				} else {
					if (!string.IsNullOrEmpty(AnchorClass)) {
						newHtml += "<span class=\"" + AnchorClass + "\">";
					}
				}
				newHtml += "<img src=\"" + ImageSrc + "\""
					+ (ImageHeight > 0 ? " height=\"" + ImageHeight + "\"" : "")
					+ (ImageWidth > 0 ? " width=\"" + ImageWidth + "\"" : "")
					+ " alt=\"" + (!string.IsNullOrEmpty(ImageAltText) ? ImageAltText : GetDefaultAltText()) + "\""
					+ (!string.IsNullOrEmpty(ImageClass) ? " class=\"" + ImageClass + "\"" : string.Empty)
					+ "/>";
				if (!string.IsNullOrEmpty(ImageLink)) {
					newHtml += "</a>";
				} else {
					if (!string.IsNullOrEmpty(AnchorClass)) {
						newHtml += "</span>";
					}
				}
				return newHtml;
			}
			set {
				_originalHtml = value;
				var imageFieldValue = new ImageFieldValue(_originalHtml);
				ImageSrc = imageFieldValue.ImageUrl;
				ImageAltText = imageFieldValue.AlternateText;
				ImageHeight = imageFieldValue.Height;
				ImageWidth = imageFieldValue.Width;
				ImageLink = imageFieldValue.Hyperlink;
			}
		}

		public string HtmlImageOnly {
			get {
				var newHtml = "<img src=\"" + ImageSrc + "\""
							+ (ImageHeight > 0 ? " height=\"" + ImageHeight + "\"" : "")
							+ (ImageWidth > 0 ? " width=\"" + ImageWidth + "\"" : "")
							+ " alt=\"" + (!string.IsNullOrEmpty(ImageAltText) ? ImageAltText : GetDefaultAltText()) + "\""
							+ (!string.IsNullOrEmpty(ImageClass) ? "\" class=\"" + ImageClass + "\"" : string.Empty)
							+ "/>";
				return newHtml;
			}
		}

		public string ImageSrc { get; private set; }

		public string ImageAltText { get; private set; }

		public int ImageWidth { get; set; }

		public int ImageHeight { get; set; }

		public string ImageLink { get; private set; }

		public string ImageClass { get; set; }

		public string AnchorClass { get; set; }

		private string GetDefaultAltText() {
			var imageName = ImageSrc.Substring(ImageSrc.LastIndexOf("/") + 1);
			imageName = imageName.Substring(0, imageName.IndexOf("."));
			return imageName;
		}

		public IComplexFieldType SetInstanceValue(object value) {
			if (value != null) {
				return new SPPublishingImageField {
					Html = value.ToString()
				};
			}
			return null;
		}

	}

}
